package fr.snac.widget;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.widget.RemoteViews;
import fr.snac.bm.BonjourActivity;
import fr.snac.bm.R;
import fr.snac.utils.Constants;
import fr.snac.utils.DateUtil;
import fr.snac.utils.FilesUtil;

public class CountDownReceiver extends BroadcastReceiver {
	
	private static String currentDate;
	
	@SuppressLint("Wakelock")
	@Override
	public void onReceive(Context context, Intent intent) {
		PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.BM_WAKE_LOCK);
		
		wl.acquire();
		
		RemoteViews rV = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
		
		String imageDate = FilesUtil.getLastPicture();
		
		if (currentDate == null || !currentDate.equals(imageDate)){
			currentDate = imageDate;
			
			if (FilesUtil.imageAlreadyDownloaded(imageDate)){

				File image = new File(FilesUtil.getImageFolderPath() + "/" + imageDate + FilesUtil.getImageType(imageDate));

				Uri madameUri = Uri.fromFile(image);
				try {
					Bitmap bmp = MediaStore.Images.Media.getBitmap(context.getContentResolver(), madameUri);
					rV.setImageViewBitmap(R.id.widgetImage, bmp);
				} catch (FileNotFoundException e) {
					//do Nothing
				} catch (IOException e) {
					//do Nothing
				}
				image = null;
			}
		}
			
		rV.setTextViewText(R.id.textWidget, DateUtil.getCountDown());
		
		ComponentName widget = new ComponentName(context, WidgetReceiver.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		
		Intent bm = new Intent(context, BonjourActivity.class);		
		PendingIntent pbm = PendingIntent.getActivity(context, 0, bm, 0);
		
		rV.setOnClickPendingIntent(R.id.widgetImage, pbm);
		
		
		manager.updateAppWidget(widget, rV);
		wl.release();
	}

}
